package com.op.teachingliteapp.sender.runnable;

import com.op.teachingliteapp.sender.listener.OnChannelStatusListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import com.op.teachingliteapp.sender.handler.ScreenSendHandler;


/**
 * Created by Genji on 2015/4/29.
 */
public class SenderRunnable implements Runnable {
    private String ip;
    private int port;
    private ScreenSendHandler screenSendHandler;
    private OnChannelStatusListener onChannelStatusListener;


    public SenderRunnable(String ip, int port) {
        this.ip = ip;
        this.port = port;
        this.screenSendHandler = new ScreenSendHandler();


    }

    public SenderRunnable(String ip,int port,  OnChannelStatusListener onChannelStatusListener) {
        this(ip, port);
        this.onChannelStatusListener = onChannelStatusListener;
        this.screenSendHandler.setOnChannelStatusListener(this.onChannelStatusListener);
    }

    public void setOnChannelStatusListener(OnChannelStatusListener onChannelStatusListener) {
        this.onChannelStatusListener = onChannelStatusListener;
        this.screenSendHandler.setOnChannelStatusListener(this.onChannelStatusListener);
    }

    @Override
    public void run() {

        EventLoopGroup group = new NioEventLoopGroup(100);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    socketChannel.pipeline().addLast(screenSendHandler);

                }
            });
            ChannelFuture future = bootstrap.connect(ip, port).sync();

//            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();

        }
// finally {
////                group.shutdownGracefully();
//
//        }


    }
}
